package servlet;

import dao.DaoMusica;
import dao.DaoTagMusica;
import entidades.Album;
import entidades.Musica;
import entidades.TagMusica;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Util;

/**
 *
 * @author Tarde
 */
@WebServlet(name = "ServletCadMusica", urlPatterns = {"/ServletCadMusica"})
public class ServletCadMusica extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String titulo = request.getParameter("titulo");
        String duracao = request.getParameter("duracao");
        String letra = request.getParameter("letra");
        String compositor = request.getParameter("compositor");
        String tags = request.getParameter("tags");
        if (Util.valida(Util.CAMPO_TEXTO, titulo) && Util.valida(Util.CAMPO_TEXTO, letra) && Util.valida(Util.CAMPO_TEXTO, compositor)
                && Util.valida(Util.CAMPO_TEXTO, tags)) {
            if (Util.valida(Util.CAMPO_DOUBLE, duracao)) {
                Double dur = Double.parseDouble(duracao);
                //Cria musica e atribui os valores a ela
                Musica musica = new Musica(titulo, dur, letra, compositor, new ArrayList<Album>(), new ArrayList<TagMusica>());
                
                //Verificar se a tagMusica existe, e existir adicionar a musica a ela, se não criar a tag
                DaoTagMusica daoTag = new DaoTagMusica();
                String[] str = tags.split(";");
                for (String name : str) {
                    String tagName = name.trim();
                    List<TagMusica> l = daoTag.buscaTagNome(tagName);
                    if (l.isEmpty()) {
                        //Cria tag e adiciona a música a ela
                        TagMusica tag = new TagMusica(tagName);
                        tag.addMusica(musica);
                        musica.addTag(tag);
                        daoTag.insert(tag);
                    } else {
                        //Adiciona a música a tag
                        TagMusica tag = l.get(0);
                        tag.addMusica(musica);
                        musica.addTag(tag);
                        daoTag.update(tag);
                    }
                }
                //Salva a música no banco de dados
                new DaoMusica().insert(musica);

                RequestDispatcher rd = request.getRequestDispatcher("homeAdmin.jsp");
                rd.forward(request, response);
            } else {
                request.setAttribute("erro", "Campo Duração inválido, favor digitar somente números com casas decimais separadas por '.' ");
                RequestDispatcher rd = request.getRequestDispatcher("cadMusica.jsp");
                rd.forward(request, response);
            }
        } else {
            request.setAttribute("erro", "Nenhum dos campos pode ser vazio");
            RequestDispatcher rd = request.getRequestDispatcher("cadMusica.jsp");
            rd.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
